package com.huxun.controller;

import com.huxun.bean.Desk;
import com.huxun.bean.Item;
import com.huxun.bean.Order;
import com.huxun.service.CartService;
import com.huxun.service.ItemService;
import com.huxun.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@Scope("prototype")
public class OrderController {
    @Autowired
    CartService cartService;
    @Autowired
    OrderService orderService;
    @Autowired
    ItemService itemService;
    @RequestMapping("/genernateOrder")
    public void genernateOrder(HttpSession session, HttpServletResponse response)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        Desk desk = (Desk) session.getAttribute("desk");
        int size = cartService.getCarts((int) desk.getId()).size();
        int desk_id = (int) desk.getId();
        int count = orderService.addOrder(desk_id);
        if (count==size+1){
            response.getWriter().write("<script>alert('下单成功！');location.href='/findOrders';</script>");
        }else {
            response.getWriter().write("<script>alert('下单失败！');location.href='/my_carts';</script>");
        }
    }

    /*
    * 订单展示页面
    * */
    @RequestMapping("/findOrders")
    public String findOrders(HttpSession session, Model model){
        Desk desk = (Desk) session.getAttribute("desk");
        int desk_id = (int) desk.getId();

        Order order = orderService.getByDeskId(desk_id);
        List<Item> items = itemService.findItems(order.getOid());
        model.addAttribute("order",order);
        model.addAttribute("items",items);
        return "clientOrderList";
    }

}
